package com.jh.user.service;

import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.jh.user.business.UserBalanceBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.User;
import com.jh.user.pojo.UserAccount;
import com.jh.user.util.Util;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.ExceptionUtil;
import cn.jh.common.utils.TokenUtil;


@Controller
@EnableAutoConfiguration
public class UserBalanceService {

	private static final Logger LOG = LoggerFactory.getLogger(UserBalanceService.class);
	
	@Autowired 
	private UserBalanceBusiness userBalBusiness;
	
	@Autowired
	private UserLoginRegisterBusiness userLoginRegisterBusiness;
	
	@Autowired
	private UserJpushService userJpushService;
	
	@Autowired
	 Util util;
	
	/**获取用户当前账户信息*/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/user/account/query/{token}")
	public @ResponseBody Object queryUserAccount(HttpServletRequest request,   
			@PathVariable("token") String token){		
	
		Map map = new HashMap();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;		
		}	
		
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserAccountByUserid(userId));
		return map;
	
	}
	/**获取用户当前账户信息*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/query/userId")
	public @ResponseBody Object queryUserAccountByUserId(HttpServletRequest request,   
			@RequestParam(value = "user_id") long userId){		
		Map<String,Object> map = new HashMap<String,Object>();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);
		if (userAccount == null) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "无该账户");
		}else {
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESULT, userAccount);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
		}
		return map;
	
	}
	
	/**获取用户当前账户信息*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/query/phone")
	public @ResponseBody Object queryUserAccountByPhone(HttpServletRequest request,   
			@RequestParam(value = "phone") String phone,
			@RequestParam(value = "brand_id", defaultValue = "-1", required=false) long brandid
			){		
	    
		Map<String,Object> map = new HashMap<String,Object>();
		User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
		long userId = user.getId();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserAccountByUserid(userId));
		return map;
	
	}
	
	
	
	
	/**锁定当前用户的账户信息*/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/user/account/lock/{token}")
	public @ResponseBody Object lockUserAccount(HttpServletRequest request,   
			@PathVariable("token") String token){		
		
		
		Map map = new HashMap();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;		
		}	
		
	
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.lockUserAccount(userId));
		return map;
	}
	
	
	
	/**将用户的钱冻结到冻结账户里面 
	 * 默认的
	 * 
	 * **/
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/freeze")
	public @ResponseBody Object freeUserAccount(HttpServletRequest request,   
			@RequestParam(value = "user_id") long userId,
			@RequestParam(value = "amount") BigDecimal amount,
			@RequestParam(value = "add_or_sub",  required=false, defaultValue = "0") String addorsub,
			@RequestParam(value = "order_code",  required=false) String ordercode
			){		
		Map<String,Object> map = new HashMap<String,Object>();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		try {
			map.put(CommonConstants.RESULT, userBalBusiness.freezeUserAccount(userAccount, amount, addorsub, ordercode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
		}
		return map;
		
	
	}
	
	
	
	/**将用户的分润提现到用户的余额中间去*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/rebate/update")
	public @ResponseBody Object updateUserRebateAccount(HttpServletRequest request,   
			@RequestParam(value = "user_id") long userId,
			@RequestParam(value = "amount",  defaultValue = "0",  required=false) BigDecimal amount,	
			@RequestParam(value = "addorsub",  defaultValue = "0",  required=false) String addorsub,
			@RequestParam(value = "order_code", required=false) String ordercode
			){		
		Map map = new HashMap();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.updateUserRebateAccount(userAccount, amount,  ordercode));
		return map;
		
	
	}
	
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/rebate/unfreeze")
	public @ResponseBody Object unfreezeUserbateAccount(HttpServletRequest request,   
			@RequestParam(value = "user_id") long userId,
			@RequestParam(value = "amount") BigDecimal amount,
			@RequestParam(value = "add_or_sub",  required=false, defaultValue = "0") String addorsub,
			@RequestParam(value = "order_code",  required=false) String ordercode
			){		
		Map map = new HashMap();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		try {
			map.put(CommonConstants.RESULT, userBalBusiness.freezeUserRebateAccount(userAccount, amount, addorsub, ordercode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
		}
		return map;
	}
	
	
	
	/**分润提现, 如果满足需求先将钱直接冻结到帐户里面*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/rebate/freeze")
	public @ResponseBody Object freezeAccountRebateBalance(HttpServletRequest request,
		@RequestParam(value = "user_id") long userId, 
		@RequestParam(value = "realamount") String realamount,  
		@RequestParam(value = "order_code") String ordercode
		){	
		
		UserAccount userAcct = userBalBusiness.rebateFreezeAccount(userId, new BigDecimal(realamount),  ordercode);
		Map map = new HashMap();

		/**提现失败 */
		if(userAcct != null){
			
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, userAcct);
			
		}else{
			
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "余额不足");
	
		}
		
		
		
		return map;
		
		
	}
	
	
	/**提现请求, 如果满足需求先把钱冻结到账户里面**/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/withdraw/freeze")
	public @ResponseBody Object freezeAccountBalance(HttpServletRequest request,
		@RequestParam(value = "user_id") long userId, 
		@RequestParam(value = "realamount") String realamount,  
		@RequestParam(value = "order_code") String ordercode
		){		
	
		UserAccount userAcct = userBalBusiness.withdrawFreeAccount(userId, new BigDecimal(realamount),  ordercode);
		Map map = new HashMap();

		/**提现失败 */
		if(userAcct != null){
			
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, userAcct);
			
		}else{
			
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "余额不足");
	
		}
		
		
		
		return map;
	
	}
	
	
	
	/**更新用户的账户信息 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/account/update")
	public @ResponseBody Object updateUserAccount(HttpServletRequest request,   
			@RequestParam(value = "user_id") long userId,
			@RequestParam(value = "amount",  defaultValue = "0",  required=false) BigDecimal amount,	
			@RequestParam(value = "addorsub",  defaultValue = "0",  required=false) String addorsub,
			@RequestParam(value = "order_code", required=false) String ordercode
			){		
		Map<String,Object> map = new HashMap<String,Object>();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		try {
			map.put(CommonConstants.RESULT, userBalBusiness.updateUserAccount(userAccount, amount,  addorsub, ordercode));
		} catch (Exception e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "更改用户帐户异常!");
			return map;
		}
		if(addorsub.equals("0")){
			/**
			 * 推送消息
			 * /v1.0/user/jpush/tset
			 * */
			String alert ="余额充值";  
			String content = "亲爱的会员，您的账户到账"+amount.setScale(2,BigDecimal.ROUND_DOWN)+"元";
			String btype="balanceadd";
			String btypeval="";
			try {
				userJpushService.setJpushtest(request, userId, alert, content, btype, btypeval);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
		
	
	}

	
	/**查询交易变更历史*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/balance/query/{token}")
	public @ResponseBody Object pageBalanceQuery(HttpServletRequest request,  
			 @PathVariable("token") String token,
			 @RequestParam(value = "page", defaultValue = "0", required = false) int page,
			 @RequestParam(value = "size", defaultValue = "20", required = false) int size,
			 @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			 @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty			
			){
		
		Map map = new HashMap();
		long userId;
		try{
			userId = TokenUtil.getUserId(token);
		}catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;		
		}
		
		Pageable pageable = new PageRequest(page, size, new Sort(direction,sortProperty));
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userBalBusiness.queryUserBalHistoryByUserid(userId, pageable));
		return map;
	}
	/**查询交易收益*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/balance/profit/{token}")
	public @ResponseBody Object pageBalanceQuery(HttpServletRequest request,  
			 @PathVariable("token") String token
			){
			Map<String, Object> map = new HashMap<String, Object>();
			long userId;
			try{
				userId = TokenUtil.getUserId(token);
			}catch (Exception e) {
				map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
				map.put(CommonConstants.RESP_MESSAGE, "token无效");
				return map;		
			}
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, userBalBusiness.findSumUserBalByUserId(userId));
			
		return map;
	}
	
	
}
